//
//  ChatuViewController.m
//  XRSquare
//
//  Created by 穆相臣 on 2018/8/22.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "ChatuViewController.h"
#import <Qiniu/QiniuSDK.h>
#import "TuCollectionViewCell.h"
static NSString * identifer = @"img";

@interface ChatuViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,deleteDelegate>
{
    UIButton * addButton;
    UICollectionView * imageCollection;
    NSMutableArray * arr;
    NSMutableArray * imgArr;
}
@end

@implementation ChatuViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        arr = [NSMutableArray array];
        imgArr = [NSMutableArray array];
    }
    return self;
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    self.navigationItem.title = @"插图";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(postAction)];
    
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;

    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(ScreenWidth/2, ScreenWidth/2);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    imageCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, rectNav.size.height + rectStatus.size.height, ScreenWidth, ScreenHeight -  rectNav.size.height - rectStatus.size.height) collectionViewLayout:layout];
    imageCollection.delegate = self;
    imageCollection.dataSource = self;
    imageCollection.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
    [self.view addSubview:imageCollection];
    
    [imageCollection registerClass:[TuCollectionViewCell class] forCellWithReuseIdentifier:identifer];
    [self request];
}

-(void)request
{
    [NetRequestCenter activityphotowithtaskid:self.contentId result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            for (NSString * str in [resultDic objectForKey:@"data"])
            {
                [arr addObject:[str stringByReplacingOccurrencesOfString:@"https://pic.xrsquare.com/" withString:@""]];
            }
            [imageCollection reloadData];
        }
    }];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [arr count] + 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TuCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];
    cell.delegate = self;
    cell.imageIndex = indexPath.item;
    if (indexPath.item == [arr count])
    {
        [cell loadAdd];
    }
    else
    {
        [cell loadData:[arr objectAtIndex:indexPath.item]];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == [arr count])
    {
        [self selectImage];
    }
}

-(void)selectImage
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * timeOrder = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * collectionOrder = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Cancel Action");
    }];
    
    [alertController addAction:timeOrder];
    [alertController addAction:collectionOrder];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:picker completion:nil];
    
    [NetRequestCenter uptokenwithbucket:@"0" result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            NSString * token = [resultDic objectForKey:@"uptoken"];
            NSData * imageData = UIImageJPEGRepresentation(selectedImage, 0.5);
            QNUploadOption * option=[[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                NSLog(@"key=%@ ,percent=%f",key,percent);
            }];
            
            QNUploadManager * upload=[[QNUploadManager alloc] init];
            
            [upload putData:imageData key:[[token componentsSeparatedByString:@":"]firstObject] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *res) {
                NSLog(@"statusCode=%d",info.statusCode);
                NSLog(@"%@",res);
                
                if(info.statusCode==200)
                {
                    [arr addObject:[res objectForKey:@"hash"]];
                    [imageCollection reloadData];
                }
                
            } option:option];
        }
    }];
}

-(void)postAction
{
    
    [NetRequestCenter activityphotowithtaskid:self.contentId pic:arr result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
